﻿

//function InitStoreTypeCombobox() {
//    $('#StoreType').combobox({
//        url: "/LkGlobal/GetStoreTypeList",
//        valueField: 'Value',
//        textField: 'Description',
//        onSelect: function (rec) {
//            //$('#StoreType').combobox("setValue", rec.Value);
//        }
//    })
//}

function InitStoreTypeCombobox(domId) {
    if (domId == undefined) {
        domId = "";
    }
    $('#StoreType' + domId).combobox({
        url: "/LkGlobal/GetStoreTypeList",
        valueField: 'Value',
        textField: 'Description',
        onSelect: function (rec) {
            //$('#StoreType').combobox("setValue", rec.Value);
        }
    })
}

function InitStoreAlgorithmCombobox() {
    $('#StoreAlgorithm').combobox({
        url: "/LkGlobal/GetStoreAlgorithmList",
        valueField: 'Value',
        textField: 'Description',
        onSelect: function (rec) {
            //$('#ColdStorage').combobox("setValue", rec.Value);
        }
    })
}

function InitCustomer(selectfn) {
    $('#CustomerId').combogrid({
        url: "/Customer/GetCustomerPageList",
        method: 'post',
        mode: 'remote',
        pageSize: 15,               //每页显示的记录条数，默认为10
        pageList: [10, 15, 20],       //可以设置每页记录条数的列表
        pagination: true,
        panelWidth: 500,
        toolbar: "#customerselecttoolbar2",
        idField: 'Id',
        textField: 'CustomerCode',
        onSelect: function () {
            var g = $('#CustomerId').combogrid('grid');
            var row = g.datagrid('getSelected');
            $('#CustomerId').combogrid("setValue", row.Id);
            $('#CustomerName').textbox('setValue', row.CustomerName);

            if (selectfn) {
                selectfn(row);
            }
        },
        columns: [[
            { field: 'Id', title: 'Id', hidden: true },
            { field: 'CustomerCode', title: '客户编号', width: 120, align: 'right' },
            { field: 'CustomerName', title: '客户名称', width: 150, align: 'right' }
        ]],
        fitColumns: true,
        filter: true,  // 启用搜索框
    })
}

function InitCustomerById(id, toolbar, selectfn) {
    $(id).combogrid({
        url: "/Customer/GetCustomerPageList",
        method: 'post',
        mode: 'remote',
        pageSize: 15,               //每页显示的记录条数，默认为10
        pageList: [10, 15, 20],       //可以设置每页记录条数的列表
        pagination: true,
        panelWidth: 500,
        toolbar: toolbar,
        idField: 'Id',
        textField: 'CustomerCode',
        onSelect: function () {
            var g = $(id).combogrid('grid');
            var row = g.datagrid('getSelected');

            if (selectfn) {
                selectfn(row);
            }
        },
        columns: [[
            { field: 'Id', title: 'Id', hidden: true },
            { field: 'CustomerCode', title: '客户编号', width: 120, align: 'right' },
            { field: 'CustomerName', title: '客户名称', width: 150, align: 'right' }
        ]],
        fitColumns: true,
        filter: true,  // 启用搜索框
    })
}

function InitCompanyById(id, toolbar, selectfn) {
    $(id).combogrid({
        url: "/BasicManage/GetLKCompanyPageList",
        method: 'post',
        mode: 'remote',
        pageSize: 15,               //每页显示的记录条数，默认为10
        pageList: [10, 15, 20],       //可以设置每页记录条数的列表
        pagination: true,
        panelWidth: 500,
        toolbar: toolbar,
        idField: 'Id',
        textField: 'CompanyName',
        onSelect: function () {
            var g = $(id).combogrid('grid');
            var row = g.datagrid('getSelected');

            if (selectfn) {
                selectfn(row);
            }
        },
        columns: [[
            { field: 'Id', title: 'Id', hidden: true },
            { field: 'CompanyCode', title: '公司编号', width: 120, align: 'right' },
            { field: 'CompanyName', title: '公司名称', width: 150, align: 'right' }
        ]],
        fitColumns: true,
        filter: true,  // 启用搜索框
    })
}

function InitWareHouse(domId) {
    if (domId == undefined) {
        domId = "";
    }
    $('#WareHouseId' + domId).combotree({
        url: "/BasicManage/GetHouseComboxTree",
        editable: false,
        valueField: 'Id',
        textField: 'WareHouseName',
        onSelect: function (rec) {
        }
    })
}

function InitSelectWareHouse() {
    $('#SelectWareHouseId').combotree({
        url: "/BasicManage/GetHouseComboxTree",
        editable: false,
        valueField: 'Id',
        textField: 'WareHouseName',
        onSelect: function (rec) {
        }
    })
}

function InitSelectCustomer(id) {
    if (id == undefined) {
        id = "SelectCustomer";
    }
    $('#' + id).combogrid({
        url: "/Customer/GetCustomerPageList",
        method: 'post',
        mode: 'remote',
        pageSize: 15,               //每页显示的记录条数，默认为10
        pageList: [10, 15, 20],       //可以设置每页记录条数的列表
        pagination: true,
        panelWidth: 500,
        toolbar: "#customerselecttoolbar",
        idField: 'Id',
        textField: 'CustomerName',
        columns: [[
            { field: 'Id', title: 'Id', hidden: true },
            { field: 'CustomerCode', title: '客户编号', width: 120, align: 'right' },
            { field: 'CustomerName', title: '客户名称', width: 150, align: 'right' }
        ]],
        fitColumns: true,
        filter: true  // 启用搜索框
    })
}

function InitChargingUnitCombobox(id) {
    if (id == undefined) {
        id = "";
    }
    $('#ChargingUnit' + id).combobox({
        url: "/LkGlobal/GetChargeUnitList",
        valueField: 'Value',
        textField: 'Description',
        onSelect: function (rec) {
            //$('#ChargingUnit').combobox("setValue", rec.Value);
        }
    })
}

function InitChargingUnitComboboxById(id) {
    if (id == undefined) {
        id = "";
    }
    $('#' + id).combobox({
        url: "/LkGlobal/GetChargeUnitList",
        valueField: 'Value',
        textField: 'Description',
        onSelect: function (rec) {
            //$('#ChargingUnit').combobox("setValue", rec.Value);
        }
    })
}

function InitColdAlgorithmCombobox() {
    $('#ColdAlgorithm').combobox({
        url: "/LkGlobal/GetColdAlgorithmList",
        valueField: 'Value',
        textField: 'Description',
        onSelect: function (rec) {
            //$('#ColdStorage').combobox("setValue", rec.Value);
        }
    })
}

function InitCostTypesCombogrid(id) {
    $("#CostType" + id).combogrid({
        //panelWidth: 1200,
        idField: 'Id',
        textField: 'CostTypeName',
        url: '/BasicManage/GetLKCostTypes',
        method: 'post',
        mode: 'remote',
        columns: [[
            { field: 'Id', title: 'Id', hidden: true },
            { field: 'CostTypeName', title: '类型', width: 80, align: 'right' }
        ]],
        onSelect: function (rowIndex, rowData) {
            $("#CostTypeId" + id).val(rowData.Id);//combobox('setValue', rowData.Id);
            $("#CostType" + id).combobox('setValue', rowData.CostTypeName);
            $("#Unit" + id).textbox('setValue', rowData.UnitName);
            $("#Price" + id).numberbox('setValue', rowData.UnitPrice);
        },
        fitColumns: true,
        labelPosition: 'top'
    });
}

function InitCostTypesCombogrid2(id, selectfn) {
    $("#CostType" + id).combogrid({
        //panelWidth: 1200,
        idField: 'Id',
        textField: 'CostTypeName',
        url: '/BasicManage/GetLKCostTypes',
        method: 'post',
        mode: 'remote',
        columns: [[
            { field: 'Id', title: 'Id', hidden: true },
            { field: 'CostTypeName', title: '类型', width: 80, align: 'right' }
        ]],
        onSelect: function (rowIndex, rowData) {
            if (selectfn) {
                selectfn({ data: rowData, did: id });
            }
        },
        fitColumns: true,
        labelPosition: 'top'
    });
}

function InitCostTypesCombogridById(idname, id, selectfn) {
    $("#" + idname).combogrid({
        //panelWidth: 1200,
        idField: 'Id',
        textField: 'CostTypeName',
        url: '/BasicManage/GetLKCostTypes',
        method: 'post',
        mode: 'remote',
        columns: [[
            { field: 'Id', title: 'Id', hidden: true },
            { field: 'CostTypeName', title: '类型', width: 80, align: 'right' }
        ]],
        onSelect: function (rowIndex, rowData) {
            if (selectfn) {
                selectfn({ data: rowData, did: id });
            }
        },
        fitColumns: true,
        labelPosition: 'top'
    });
}

//商品
function InitGoods(id) {
    if (id == undefined) {
        id = "";
    }
    $('#GoodsId' + id).combogrid({
        url: "/BasicManage/GetLKGoodsPageList",
        method: 'post',
        mode: 'remote',
        pageSize: 15,               //每页显示的记录条数，默认为10
        pageList: [10, 15, 20],       //可以设置每页记录条数的列表
        pagination: true,
        panelWidth: 500,
        //toolbar: "#customerselecttoolbar2",
        idField: 'Id',
        textField: 'GoodsName',
        onSelect: function (rowIndex, rowData) {
            $('#GoodsId').combogrid("setValue", rowData.Id);
        },
        columns: [[
            { field: 'Id', title: 'Id', hidden: true },
            { field: 'GoodsCode', title: '商品编号', width: 120, align: 'right' },
            { field: 'GoodsName', title: '商品名称', width: 150, align: 'right' }
        ]],
        fitColumns: true,
        filter: true,  // 启用搜索框
    })
}

//商品规格
function InitGoodsSpecCombobox(id) {
    if (id == undefined) {
        id = "";
    }
    $('#GoodsSpecId' + id).combobox({
        url: "/BasicManage/GetLKGoodsSpec",
        valueField: 'Id',
        textField: 'SpecName',
        onSelect: function (rec) {
            //$('#ChargingUnit').combobox("setValue", rec.Value);
        }
    })
}

function formatdate(value) {
    var date = new Date(value);//long转换成date
    var year = date.getFullYear().toString();
    var month = (date.getMonth() + 1);
    var day = date.getDate().toString();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    //console.log(year);
    if (year == 1911) {
        return "";
    }
    return year + "-" + month + "-" + day;
}

function checkDecimal(newValue, oldValue) {
    if (newValue.toString().split('.').length > 1) {
        var decimalPart = newValue.toString().split('.')[1];
        if (decimalPart.length > 2) {
            $(this).numberbox('setValue', oldValue);
        }
    }
}

function setFixRate() {
    //	var value = $('._fixRate').numberbox('getValue');//不能使用numberbox的getValue,这个是隐藏框的值
    //如果有小数点
    var value = $('#Balance').val();//这个才是输入框的值
    if (value.indexOf(".") >= 0) {//如果包含小数点
        if ((value.substring(value.indexOf(".") + 1).length) >= 2) {//如果小数位数已经有两位
            //			window.event.returnValue = false;
            //			$('._fixRate').val(value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'));
            //			$('._fixRate').numberbox('filter',false);
            $('#Balance').numberbox('options').filter = function () {
                //让filter返回false会禁止按键输入
                return false;
            };
        } else {
            //记得写else,否则该nunberbox将不允许再次输入了
            $('#Balance').numberbox('options').filter = function () {
                return true;
            }
        }
    }
}

function fileChange() {
    var formData = new FormData($("#fm")[0]);
    //formData.append("file", $("#filebox")[0].files[0]);
    $.ajax({
        type: 'post',
        url: "/Attachment/UploadFile",
        data: formData,
        cache: false,
        processData: false,
        contentType: false,
    }).success(function (data) {
        $("#hidFileId").val(data.id);
    }).error(function () {
        alert("上传失败");
    });
}


//按周期分割日期
function dateCutByMonth2(beginDate, endDate) {
    let _beginDate = []
    let _endDate = []
    let monthNum = mouthDifferCount(beginDate, endDate)
    if (monthNum) {
        _beginDate = getBeginDate(monthNum, beginDate, endDate)
        _endDate = getEndDate(beginDate, _beginDate, endDate)
    } else {
        _endDate = [{ beginDate, endDate }]
    }
    return _endDate
};

// 计算每个月的开始时间
function getBeginDate(numMonth, beginDate, endDate) {
    let _beginDay = beginDate.split('-')[2]
    let _endDya = endDate.split('-')[2]
    let nextForDate = beginDate
    let dateCutList = []
    for (let i = 0; i < numMonth; i++) {
        var now = new Date(nextForDate); // 能够传值调式 now = new Date(2019,2,30); 今天是3月30号
        var year = now.getFullYear();//getYear()+1900=getFullYear()
        var month = now.getMonth() + 1;//0-11表示1-12月
        // var day = now.getDate(); // 当天日期
        var day = _beginDay

        if (parseInt(month) < 10) {
            month = "0" + month;
        }

        now = year + '-' + month + '-' + day; // 若是取当月日期可直接 return 返回

        var nextMonth = parseInt(month) + 1;
        nextMonth = nextMonth < 10 ? '0' + nextMonth : nextMonth; // 获取下个月个月的值
        if (nextMonth > 12) {
            year += 1
            nextMonth = '01'
        }
        var nextSize = new Date(year, parseInt(month) + 1, 0).getDate();//下月总天数
        if (nextSize < parseInt(day)) { // 若是下个月总天数小于本月今天，取下个月最后一天  
            nextForDate = year + '-' + nextMonth + '-' + nextSize;
            dateCutList.push(nextForDate);
        } else if (nextSize >= parseInt(day)) {
            nextForDate = year + '-' + nextMonth + '-' + day;
            dateCutList.push(nextForDate);
        }
    }
    return dateCutList
}

// 计算每个月的结束时间
function getEndDate(beginDate, dateList, endDate) {
    let _dateList = []
    dateList.unshift(beginDate)
    dateList.forEach((item, index) => {
        // if (dateList[index + 1]) {
        let date1 = new Date(dateList[index + 1])
        let date2 = new Date(date1.getTime() - 24 * 60 * 60 * 1000)
        let y2 = date2.getFullYear();
        let m2 = date2.getMonth() + 1 < 10 ? "0" + (date2.getMonth() + 1) : date2.getMonth() + 1;
        let d2 = date2.getDate() < 10 ? "0" + date2.getDate() : date2.getDate();
        let endDate = y2 + "-" + m2 + "-" + d2
        _dateList.push({ "beginDate": item, "endDate": endDate })
        // }
    })
    _dateList[_dateList.length - 1]['endDate'] = endDate
    let endBeginDateGetTime = new Date(_dateList[_dateList.length - 1]['beginDate']).getTime()
    let endDateGetTime = new Date(_dateList[_dateList.length - 1]['endDate']).getTime()
    if (endBeginDateGetTime >= endDateGetTime) {
        _dateList.pop()
    }
    return _dateList;
}

// 计算两个月份相差时间差
function mouthDifferCount(startDate, endDate) {
    startDate = startDate.split('-');
    // 得到月数
    startDate = parseInt(startDate[0]) * 12 + parseInt(startDate[1]);
    // 拆分年月日
    endDate = endDate.split('-');
    // 得到月数
    endDate = parseInt(endDate[0]) * 12 + parseInt(endDate[1]);
    var times = Math.abs(startDate - endDate);
    return times
}


/**
* 将指定日期区间按月份分割
*/
function dateCutByMonth(beginDate, endDate) {
    //分割好的数组
    var dateCutList = new Array();

    var b_date = new Date(beginDate);
    var e_date = new Date(endDate);
    //获取各个的年份
    var b_year = parseInt(b_date.getFullYear());
    var e_year = parseInt(e_date.getFullYear());
    //获取各个的月份
    var b_month = parseInt(b_date.getMonth()) + 1;
    var e_month = parseInt(e_date.getMonth()) + 1;

    //获取日期之间想差的月数；
    var month_list = monthList();
    //按月份分割日期
    for (var i = 0; i < month_list.length; i++) {
        //当前月开始日期：第一天
        var i_b_date = new Date(month_list[i]);
        i_b_date.setDate(1);
        //当前月最后一天
        var i_e_date = new Date(month_list[i]);
        i_e_date.setMonth(i_e_date.getMonth() + 1);
        i_e_date.setDate(1);
        i_e_date.setDate(i_e_date.getDate() - 1);

        //第一次循环：开始月份
        if (i == 0) {
            var i_e_ymd = parseTime(i_e_date).split(" ")[0];
            dateCutList.push({ "beginDate": beginDate, "endDate": i_e_ymd });

            //除第一次和最后一次循环：中间月份	
        } else if (i != 0 && i != month_list.length - 1) {
            var i_b_ymd = parseTime(i_b_date).split(" ")[0];
            var i_e_ymd = parseTime(i_e_date).split(" ")[0];
            dateCutList.push({ "beginDate": i_b_ymd, "endDate": i_e_ymd });

            //   //最后一次循环：结束月份
        } else if (i == month_list.length - 1) {
            var i_b_ymd = parseTime(i_b_date).split(" ")[0];
            dateCutList.push({ "beginDate": i_b_ymd, "endDate": endDate });
        }
    }
    console.log(dateCutList);
    return dateCutList;

    //---------------------------------------------------------------------------------------------------
    //-------------------------------以下为工具函数-------------------------------------------------------
    //---------------------------------------------------------------------------------------------------

    /**
     * 获取日期区间的月份集合
     */
    function monthList() {

        //相差的月份总数
        var result = new Array();

        var b = new Date(b_year, b_month - 1, 1);
        var e = new Date(e_year, e_month - 1, 1);
        while (b < e) {
            result.push(b.getFullYear() + "-" + (b.getMonth() + 1));
            b.setMonth(b.getMonth() + 1);
        }
        result.push(e_year + "-" + e_month);
        return result;
    }

    /**
     * 日期格式化方法 
     */
    function parseTime(time, pattern) {
        if (arguments.length === 0 || !time) {
            return null
        }
        const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
        let date
        if (typeof time === 'object') {
            date = time
        } else {
            if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
                time = parseInt(time)
            } else if (typeof time === 'string') {
                time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
            }
            if ((typeof time === 'number') && (time.toString().length === 10)) {
                time = time * 1000
            }
            date = new Date(time)
        }
        const formatObj = {
            y: date.getFullYear(),
            m: date.getMonth() + 1,
            d: date.getDate(),
            h: date.getHours(),
            i: date.getMinutes(),
            s: date.getSeconds(),
            a: date.getDay()
        }
        const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
            let value = formatObj[key]
            // Note: getDay() returns 0 on Sunday
            if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
            if (result.length > 0 && value < 10) {
                value = '0' + value
            }
            return value || 0
        })
        return time_str
    }
}